package com.guigu.qingcheng.controller;

import com.guigu.qingcheng.service.GoodsServiceFeign;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.Map;

@Controller
public class SearchController {

    @Resource
    private GoodsServiceFeign goodsServiceFeign;

    @GetMapping("search")
    public String search(Model model, @RequestParam Map<String, String> searchMap) {
        if (searchMap.get("pageNo")==null) {
            searchMap.put("pageNo","1");
        }
        //排序参数容错处理
        if(searchMap.get("sort")==null){
            searchMap.put("sort","");
        }
        if(searchMap.get("sortOrder")==null){
            searchMap.put("sortOrder","DESC");
        }
        Map resultMap = goodsServiceFeign.search(searchMap);
        model.addAttribute("result", resultMap);

        //url处理
        StringBuffer url=new StringBuffer("/search?");
        for(String key:searchMap.keySet()){
            url.append( "&"+key+"="+ searchMap.get(key) );
        }
        model.addAttribute("url",url);

        model.addAttribute("searchMap",searchMap);
        // 页码
        int pageNo = Integer.parseInt(searchMap.get("pageNo"));
        model.addAttribute("pageNo",pageNo);

        Long totalPages= Long.parseLong(resultMap.get("totalPages").toString());//得到总页数
        int startPage = 1; // 开始页码
        int endPage = totalPages.intValue(); // 截至代码
        if (totalPages>5) {
            startPage = pageNo - 2;
            if (startPage<1){
                startPage = 1;
            }
            endPage = startPage + 4;
        }
        model.addAttribute("startPage", startPage);
        model.addAttribute("endPage",endPage);



        return "search";
    }
}
